package be.kuleuven.thesis.databases;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import be.kuleuven.thesis.framework.Album;

public class JSONParser {
	public static void setMetaData(Album album, String jString) {
		if(jString == null || jString.equals(""))
			return;
		try {
			JSONObject jObject = new JSONObject(jString);
			if(jObject.has("error")) {
				album.setName("Unknown");
			} else {
				JSONObject jTrack = jObject.getJSONObject("track");
				if(!jTrack.has("album"))
					album.setName("Unknown");
				else {
					JSONObject jAlbum = jTrack.getJSONObject("album");
					album.setArtist(jAlbum.getString("title"));
					album.setName(jAlbum.getString("title"));
					JSONArray jImage = jAlbum.getJSONArray("image");
					album.setSmallImageUrl(jImage.getJSONObject(1).getString("#text"));
					album.setLargeImageUrl(jImage.getJSONObject(2).getString("#text"));
				}
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
	
	public static void setImages(Album album, String jString) {
		if(jString == null || jString.equals(""))
			return;
		try {
			JSONObject jObject = new JSONObject(jString);
			if(jObject.has("error")) {
				album.setSmallImageUrl("not found");
				album.setLargeImageUrl("not found");
			} else {
				JSONArray jImage = jObject.getJSONObject("artist").getJSONArray("image");
				album.setSmallImageUrl(jImage.getJSONObject(1).getString("#text"));
				album.setLargeImageUrl(jImage.getJSONObject(2).getString("#text"));
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
}
